<?php


namespace App\Services;

use App\Models\FileGoodsEdit;
use App\Models\FileGoodsEditError;
use Illuminate\Support\Facades\DB;
use App\Jobs\ImportGoods;
use App\Imports\GoodsImport;
use Illuminate\Http\UploadedFile;
use App\Utils\Code;
use Illuminate\Support\Str;

class GoodsImportEditService extends BaseService
{
    public function importEdit(UploadedFile $file, array $params = []) {
        if (FileGoodsEdit::where('status', 0)->exists()) {
            throw new \Exception('检测到已有表格导入数据正在执行，为避免重复出错，请在上一个导表执行完毕后再导入新表', Code::PARAMETER_ERROR);
        }
        return \DB::transaction(function () use ($file, $params) {
            $fileName = Str::random(40).'.'.$file->getClientOriginalExtension();
            $datePath = date('Y/m/d');
            $fileInfo = new FileGoodsEdit();
            $fileInfo->user_id = $this::$user->user_id;
            $fileInfo->name = $file->getClientOriginalName();
            $fileInfo->path = $file->storeAs($datePath, $fileName, ['disk'=>'excel']);
            $fileInfo->status = 0;
            $fileInfo->save();
            $filePath = public_path("/storage/excels/{$fileInfo->path}");
            if (isset($params['mode']) && $params['mode'] == 'async') {
                ImportGoods::dispatch($fileInfo);
            } else {
                \Excel::import(new \App\Imports\GoodsImportEdit($fileInfo), $filePath);
                $fileInfo->status = 1;
                $fileInfo->save();
            }
            return FileGoodsEdit::where('file_id', $fileInfo->file_id)->first();
        });
    }
    
    /**
     * 商品文件分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function filePaginate(array $params = []) {
        $model = new FileGoodsEdit();
        if (key_exists('status', $params) && is_numeric($params['status'])) {
            $model = $model->where('status', $params['status']);
        }
        if (isset($params['type']) && $params['type']) {
            $model = $model->where('type', $params['type']);
        }
        if (isset($params['created_at']) && $params['created_at'] && is_array($params['created_at'])) {
            if (isset($params['created_at'][0]) && $params['created_at'][0]) {
                $model = $model->where('created_at', '>=', $params['created_at'][0]);
            }
            if (isset($params['created_at'][1]) && $params['created_at'][1]) {
                $model = $model->where('created_at', '<=', $params['created_at'][1]);
            }
        }
        return $model->orderBy('file_id', 'desc')
            ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
    }
    
    /**
     * 商品导入错误日志
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function errorPaginate(array $params = []) {
        $model = new FileGoodsEditError();
        if (isset($params['file_id']) && $params['file_id']) {
            $model = $model->where('file_id', $params['file_id']);
        }
        if (isset($params['created_at']) && $params['created_at'] && is_array($params['created_at'])) {
            if (isset($params['created_at'][0]) && $params['created_at'][0]) {
                $model = $model->where('created_at', '>=', $params['created_at'][0]);
            }
            if (isset($params['created_at'][1]) && $params['created_at'][1]) {
                $model = $model->where('created_at', '<=', $params['created_at'][1]);
            }
        }
        return $model->orderBy('file_id', 'desc')
            ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
    }
}
